/*
 * @Author: YuDianyun
 * @Email: 44208156@qq.com
 * @Date: 2020-05-29 09:00:00
 * @Last Modified by: YuDianyun
 * @Last Modified time: 2020-05-29 16:00:00
 * @Description: 图片查看、编辑
 */
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/services.dart';
import 'package:flutter_code_framework/route/route_transition.dart';
import 'package:flutter_code_framework/utils/global.dart';
import 'package:flutter_code_framework/widgets/x_dialog_page.dart';
import 'package:flutter_sfsymbols/flutter_sfsymbols.dart';
import 'package:flutter_speed_dial/flutter_speed_dial.dart';
import 'package:painter/painter.dart';
import 'package:flutter/rendering.dart';
import 'package:permission_handler/permission_handler.dart';
import 'dart:ui' as ui;
import 'package:extended_image/extended_image.dart';

typedef void GetPickImagePath(ByteData bytes);
typedef void GetScanImagePath(String path);
enum ImageType { scan, edit }

// ignore: must_be_immutable
class ImageWidget extends StatefulWidget {
  final ImageType imageType;
  GetPickImagePath callback;
  GetScanImagePath scanCallback;
  String imageUrl;

  ImageWidget(
      {Key key,
      this.imageType = ImageType.scan,
      this.imageUrl,
      this.callback,
      this.scanCallback})
      : super(key: key);

  @override
  _ImageWidgetState createState() => new _ImageWidgetState();
}

class _ImageWidgetState extends State<ImageWidget> {
  PainterController _controller;

  GlobalKey _globalKey = GlobalKey();
  final GlobalKey<ExtendedImageEditorState> editorKey =
      GlobalKey<ExtendedImageEditorState>();

  @override
  void initState() {
    super.initState();
    _controller = _newController();
    var a = Colors.transparent;
// //一直保持黑色状态栏
//   SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
    PermissionHandler().requestPermissions(<PermissionGroup>[
      PermissionGroup.storage, // 在这里添加需要的权限
    ]);
  }

  PainterController _newController() {
    PainterController controller = new PainterController();
    controller.thickness = 5.0;
    controller.backgroundColor = Colors.transparent;
    controller.drawColor = Colors.red;
    return controller;
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> actions;
    if (widget.imageType == ImageType.edit) {
      // actions = <Widget>[
      //   new IconButton(
      //       icon: new Icon(
      //         Icons.undo,
      //       ),
      //       tooltip: 'Undo',
      //       onPressed: () {
      //         if (_controller.isEmpty) {
      //         } else {
      //           _controller.undo();
      //         }
      //       }),
      //   new IconButton(
      //       icon: new Icon(Icons.delete),
      //       tooltip: 'Clear',
      //       onPressed: _controller.clear),
      //   new IconButton(
      //       icon: new Icon(Icons.rotate_left),
      //       tooltip: 'Rotate Left',
      //       onPressed: () => {editorKey.currentState.rotate(right: false)}),
      //   new IconButton(
      //       icon: new Icon(Icons.rotate_right),
      //       tooltip: 'Rotate Right',
      //       onPressed: () => {editorKey.currentState.rotate(right: true)}),
      //   new IconButton(
      //       icon: new Icon(Icons.check), onPressed: () => _saveScreen()),
      // ];

      actions = <Widget>[
        Container(
          alignment: Alignment.centerRight,
          padding: EdgeInsets.only(right: 24.0),
          child: GestureDetector(
            child: Text(
              "完成",
              style: TextStyle(
                color: G.ADColor("#438D76"),
                fontSize: 14.0,
              ),
            ),
            onTap: _saveScreen,
          ),
        )
      ];
    } else {
      actions = <Widget>[
        Container(
          alignment: Alignment.centerRight,
          padding: EdgeInsets.only(right: 24.0),
          child: GestureDetector(
            child: Text(
              "删除",
              style: TextStyle(
                color: G.ADColor("#438D76"),
                fontSize: 14.0,
              ),
            ),
            onTap: _del,
          ),
        )
      ];
    }
    Widget painter;
    if (widget.imageType == ImageType.edit) {
      painter = Painter(_controller);
    } else {
      painter = Container();
    }
    return new Scaffold(
      appBar: new AppBar(
        backgroundColor:G.brigtTheme.backgroundColor,// G.ADColor("d7d7d7"),
        title: const Text(''),
        actions: actions,
      ),
      floatingActionButton: (widget.imageType == ImageType.edit)
          ? SpeedDial(
              child: Icon(
                SFSymbols.pencil_outline,
                color: G.ADColor("#EC7364", alpha: 0.9),
                size: 38.0,
              ),
              marginRight: 18, //右边距
              marginBottom: 18, //下边距
              //animatedIcon: AnimatedIcons.menu_close,//带动画的按钮
              //animatedIconTheme: IconThemeData(size: 22.0),
              visible: true, //是否显示按钮
              closeManually: true, //是否在点击子按钮后关闭展开项
              //curve: Curves.bounceIn,//展开动画曲线
              overlayColor: Colors.transparent, //遮罩层颜色
              overlayOpacity: 0, //遮罩层透明度
              onOpen: () => null, //print('OPENING DIAL'), //展开回调
              onClose: () => null, //print('DIAL CLOSED'), //关闭回调
              tooltip: '编辑', //长按提示文字
              heroTag: '', //hero标记
              backgroundColor:G.ADColor("#DDDDDD",alpha:0.5),// Colors.blue, //按钮背景色
              foregroundColor: G.ADColor("#DDDDDD",alpha:0.5),//Colors.transparent, //按钮前景色/文字色
              elevation: 8.0, //阴影
              //shape: CircleBorder(),//shape修饰

              children: [
                  SpeedDialChild(
                    child: Icon(Icons.delete,color: G.ADColor("#B5B5B5"),),
                    backgroundColor: G.ADColor("#DDDDDD",alpha:0.5),
                    //foregroundColor: G.ADColor("#B5B5B5"),
                    // label: '清除',
                    // labelStyle: TextStyle(fontSize: 18.0),
                    onTap: () => _controller.clear(),
                  ),
                  SpeedDialChild(
                    child: Icon(
                      SFSymbols.arrowshape_turn_up_left_circle,
                      color: G.ADColor("#B5B5B5"),
                      size: 38.0,
                    ),
                    backgroundColor: G.ADColor("#DDDDDD",alpha:0.5),
                    //foregroundColor: G.ADColor("#B5B5B5"),
                    //backgroundColor: Colors.red,
                    // label: '撤销',
                    // labelStyle: TextStyle(fontSize: 18.0),
                    onTap: () => {
                      if (_controller.isEmpty) {} else {_controller.undo()},
                    },
                  ),
                  SpeedDialChild(
                    child: Icon(SFSymbols.rotate_left,
                        color: G.ADColor("#39876E", alpha: 0.98), size: 34),
                    //backgroundColor: Colors.transparent,
                    // label: '左转90度',
                    // labelStyle: TextStyle(fontSize: 18.0),
                    onTap: () => {editorKey.currentState.rotate(right: false),},
                    backgroundColor: G.ADColor("#DDDDDD",alpha:0.5),
                    //foregroundColor: G.ADColor("#B5B5B5"),
                  ),
                  SpeedDialChild(
                    child: Icon(SFSymbols.rotate_right,
                        color: G.ADColor("#39876E", alpha: 0.98), size: 34),
                    //backgroundColor: Colors.transparent,
                    // label: '右转90度',
                    // labelStyle: TextStyle(fontSize: 18.0),
                    onTap: () => {editorKey.currentState.rotate(right: true)},
                    backgroundColor: G.ADColor("#DDDDDD",alpha:0.5),
                  ),
                ])
          : Container(),
      body: new Center(
        child: new RepaintBoundary(
          key: _globalKey,
          child: new Stack(
            alignment: Alignment.center,
            children: <Widget>[
              Container(
                color: Colors.transparent,
                width: MediaQuery.of(context).size.width,
                height: MediaQuery.of(context).size.height,
                child: (widget.imageUrl.indexOf("http") > -1)
                    ? ExtendedImage.network(
                        widget.imageUrl,
                        fit: BoxFit.contain,
                        mode: ExtendedImageMode.editor,
                        enableLoadState: true,
                        extendedImageEditorKey: editorKey,
                        initEditorConfigHandler: (ExtendedImageState state) {
                          return EditorConfig(
                              maxScale: 8.0,
                              cropRectPadding: const EdgeInsets.all(0.0),
                              cornerSize: Size(0.0, 0.0),
                              cornerColor: Colors.transparent,
                              lineColor: Colors.transparent,
                              lineHeight: 0.6,
                              editorMaskColorHandler: null,
                              hitTestSize: 0.0,
                              cropAspectRatio: null,
                              initCropRectType: InitCropRectType.layoutRect);
                        },
                      )
                    : ExtendedImage.file(
                        File(widget.imageUrl),
                        fit: BoxFit.contain,
                        mode: ExtendedImageMode.editor,
                        enableLoadState: true,
                        extendedImageEditorKey: editorKey,
                        initEditorConfigHandler: (ExtendedImageState state) {
                          return EditorConfig(
                              maxScale: 8.0,
                              cropRectPadding: const EdgeInsets.all(0.0),
                              cornerSize: Size(0.0, 0.0),
                              cornerColor: Colors.transparent,
                              lineColor: Colors.transparent,
                              lineHeight: 0.6,
                              editorMaskColorHandler: null,
                              hitTestSize: 0.0,
                              cropAspectRatio: null,
                              initCropRectType: InitCropRectType.layoutRect);
                        },
                      ),
              ),
              painter,
            ],
          ),
        ),
      ),
    );
  }

  _del() {
    // RouteTransition(XDialogPage(
    //   '确定要删除吗',
    //   callBack: () {
    //     widget.scanCallback(widget.imageUrl);
    //   },
    // )).pushTransRoute(context);
    G.showToastDialog(context, "确定要删除吗",title:"提示",callBack: () {widget.scanCallback(widget.imageUrl);});
    // widget.scanCallback(widget.imageUrl);
  }

  _saveScreen() async {
    RenderRepaintBoundary boundary =
        _globalKey.currentContext.findRenderObject();

    ui.Image image = await boundary.toImage();

    ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    // final result =
    //     await ImageGallerySaver.saveImage(byteData.buffer.asUint8List());
    widget.callback(byteData);
  }
}

class AspectRatioItem {
  AspectRatioItem({this.value, this.text});
  final String text;
  final double value;
}
